﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StateGrid;
using StateGrid.GDFG;
using StateGrid.User;
using StateGrid.GlobalVariables;
using iTextSharp.text.pdf;
using StateGrid.OperationLog;

public partial class AddPM : System.Web.UI.Page
{
    /// <summary>
    /// 国电法规操作对象
    /// </summary>
    private GDFG_DAO gdfgDAO = new GDFG_DAO();
    private const int FLBM_LEN = 12;
    /// <summary>
    /// 日志操作对象
    /// </summary>
    private OperationLog_DAO operationLogDAO = new OperationLog_DAO();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response);
            return;
        }

        if (!this.IsPostBack)
        {
            this.BindData();
        }

    }

    /// <summary>
    /// 绑定初始化数据
    /// </summary>
    private void BindData()
    {
        
        String message = null;
        //获取分类编码
        String flbm = Request["flbm"];
        //年份
        String nf = Request["nf"];

        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            Response.Write(" <script> top.location = '" + GlobalResource.LOGIN_PAGE + "' </script> ");
            return;
        }
        //登录人
        this.dlrTextBox.Text = user.name;

        GDFG_FL gdfgFL = null;
        //验证年份
        if (null == nf || nf.Length != 4)
        {
            message = "错误：年份信息有误";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }

        if (null == flbm || "".Equals(flbm))
        {
            message = "错误：分类编码为空";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }
        else
        {
            gdfgFL = gdfgDAO.GetGDFG_FLByFlbm(flbm);
            if (null == gdfgFL)
            {
                message = "错误：没有找到对应的分类编码";
                Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
                return;
            }
        }

        //设置返回按钮链接
        this.backHyperLink.NavigateUrl = GlobalGDFG.LISTPM_PAGE + "?catalog=" + flbm;

        GDFG_PM gdfgPM = this.gdfgDAO.getMaxGDFG_PM(flbm, nf);
       
        //分类编码
        this.flbmTextBox.Text = gdfgFL.flbm;
        //分类名称
        this.flmcTextBox.Text = gdfgFL.flmc;
        //索引编码
        while (flbm.Length < FLBM_LEN) flbm = flbm + "0";
        this.sybmTextBox.Text= flbm+'-'+nf;
        //发布年份
        this.fbnfTextBox.Text = nf;

        //法规文号
        this.fgwhTextBox.Text = "";
        //法规名称
        this.fgmcTextBox.Text = "";
        //发布单位
        this.fbdwTextBox.Text = "";
        //专业分类
        this.zyflTextBox.Text = "";
        //发布日期
        this.fbrqTextBox.Text = nf;
        //实施日期
        this.ssrqTextBox.Text = "";
        //失效日期
        this.sxrqTextBox.Text = "";
        //时效
        this.sxTextBox.Text = "";
        //开本
        this.kbTextBox.Text = "";
        //页数
        this.ysTextBox.Text = "";
        //更新项
        this.gxxTextBox.Text = "";
        //备注
        this.bzTextBox.Text = "";

        String wjm = null;
        //设置国电法规文件名
        if (null == gdfgPM)
        {
            wjm = GetWJM(null);
        }
        else
        {
            wjm = GetWJM(gdfgPM.wjm);
        }
        this.pdfTextBox.Text = wjm + ".PDF";
    }

    /// <summary>
    /// 获取用户填写的国电法规篇名信息
    /// </summary>
    /// <returns></returns>
    private GDFG_PM GetGDFGPM()
    {
        GDFG_PM gdfgPM = new GDFG_PM();
        //索引编码
        gdfgPM.sybm = this.sybmTextBox.Text;
        //分类编码
        gdfgPM.flbm = this.flbmTextBox.Text;
        //文件名
        gdfgPM.wjm = this.pdfTextBox.Text;
        //法规名称
        gdfgPM.fgmc = this.fgmcTextBox.Text.Trim();
        //法规文号
        gdfgPM.fgwh = this.fgwhTextBox.Text.Trim();
        //发布单位
        gdfgPM.fbdw = this.fbdwTextBox.Text.Trim();

        //发布日期
        if (!"".Equals(this.fbrqTextBox.Text))
            gdfgPM.fbrq = DateTime.Parse(this.fbrqTextBox.Text);
        //实施日期
        if (!"".Equals(this.ssrqTextBox.Text))
            gdfgPM.ssrq = DateTime.Parse(this.ssrqTextBox.Text);
        //失效日期
        if (!"".Equals(this.sxrqTextBox.Text))
            gdfgPM.sxrq = DateTime.Parse(this.sxrqTextBox.Text);

        //专业分类
        gdfgPM.zyfl = this.zyflTextBox.Text;
        //时效
        gdfgPM.sx = this.sxTextBox.Text.Trim();
        //开本
        gdfgPM.kb = this.kbTextBox.Text.Trim();
        //开放
        gdfgPM.kf = this.kfCheckBox.Checked;
        //全文检查
        gdfgPM.qwjc = this.qwjcCheckBox.Checked;

        if (!"".Equals(this.ysTextBox.Text))
            gdfgPM.ys = Int32.Parse(this.ysTextBox.Text);
        //更新项
        gdfgPM.gxx = this.gxxTextBox.Text;
        //备注
        gdfgPM.bz = this.bzTextBox.Text;
        //更新日期
        gdfgPM.gxrq = DateTime.Now;
        //登录人
        gdfgPM.dlr = this.dlrTextBox.Text.Trim();

        return gdfgPM;

    }

    /// <summary>
    /// 获取下一个文件名，不包括后缀
    /// </summary>
    /// <param name="wjm">文件名</param>
    /// <returns></returns>
    private String GetWJM(String wjm)
    {
        String result = null;
        if (null == wjm || "".Equals(wjm))
        {
            result = this.sybmTextBox.Text + "-001";
        }
        else
        {
            //获取文件名的后三位流水号，并在其基础上加1
            int endIndex = wjm.LastIndexOf(".");

            String phString = wjm.Substring(endIndex - 3, 3);

            int ph = 0;

            try
            {
                ph = Int32.Parse(phString);
            }
            catch (Exception)
            {
            }

            //当前篇号+1
            ph += 1;

            phString = ph.ToString();
            //长度为1
            if (phString.Length == 1)
            {
                phString = "00" + phString;
            }
            else if (phString.Length == 2)
            {
                phString = "0" + phString;
            }
            else if (phString.Length >= 3)
            {
                String message = "错误：篇名数量已经超过了1000篇";
                Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
                return null;
            }

            result = this.sybmTextBox.Text + "-" + phString;
        }
        return result;
    }

    protected void submitButton_Click(object sender, EventArgs e)
    {
        //验证文件名
        if (!this.ValidateWJM())
        {
            return;
        }
        //验证法规名称
        if (!this.ValidateFGMC())
        {
            return;
        }
        //日期验证
        if (!this.ValidateRQ(this.fbrqTextBox.Text.ToString(), "发布日期")
           || !this.ValidateRQ(this.ssrqTextBox.Text.ToString(), "实施日期")
           || !this.ValidateRQ(this.sxrqTextBox.Text.ToString(), "失效日期"))
        {
            return;
        }
        //发布年份验证
        if (!ValidateFBNF(this.fbnfTextBox.Text, this.fbrqTextBox.Text))
        {
            return;
        }

        //验证上传文件
        if (!this.ValidateYWJMFileUpload())
        {
            return;
        }

        GDFG_PM gdfgPM = this.GetGDFGPM();
        if (OperationFile.Upload(this.ywjmFileUpload, gdfgPM.wjm))
        {
            if (this.gdfgDAO.InsertGDFG_PM(gdfgPM))
            {
                Response.Write("<Script>alert('添加国电法规信息成功')</Script>");
                this.BindData();
            }
        }
        else
        {
            Response.Write("<Script>alert('添加国电法规信息失败')</Script>");
        }
    }

    /// <summary>
    /// 验证文件名
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateWJM()
    {
        Boolean flag = true;

        this.errorLabel.Text = "";
        GDFG_PM gdfgPM = this.gdfgDAO.GetGDFG_PMByWjm(this.pdfTextBox.Text);
        if (null != gdfgPM)
        {
            this.errorLabel.Text = "错误：该文件名已存在";
            flag = false;
        }
        return flag;
    }

    /// <summary>
    /// 验证法规名称
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateFGMC()
    {
        Boolean flag = true;

        this.errorLabel.Text = "";
        if(null==this.fgmcTextBox.Text||"".Equals(this.fgmcTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：法规名称不能为空";
            flag = false;
        }
        return flag;
    }

    /// <summary>验证日期</summary>
    private Boolean ValidateRQ(String rq, String msg)
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (rq != "")
        {
            try
            {
                DateTime val = DateTime.Parse(rq);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：" + msg + "格式不正确.";
                return false;
            }
        }
        return flag;
    }

    /// <summary>验证发布日期</summary>
    private Boolean ValidateFBNF(String fbnf, String fbrq)
    {
        Boolean flag = true;
        this.errorLabel.Text = "";

        if (!"".Equals(fbrq))
        {
            //保证发布年份相符
            if (fbrq.IndexOf(fbnf) < 0)
            {
                this.errorLabel.Text = "错误：发布年份与发布日期不符";
                flag = false;
            }
        }

        return flag;
    }
    
    /// <summary>验证页数</summary>
    private Boolean ValidateYS()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.ysTextBox != null && this.ysTextBox.Text != "")
        {
            try
            {
                int val = Int32.Parse(this.ysTextBox.Text);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：页数信息不是有效数字";
                return false;
            }
        }

        return flag;
    }

    /// <summary>
    /// 验证上传文件
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateYWJMFileUpload()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.ywjmFileUpload || !this.ywjmFileUpload.HasFile)
        {
            this.errorLabel.Text = "错误：请选择上传的文件";
            flag = false;
        }
        else
        {
            if (!this.ywjmFileUpload.FileName.EndsWith(".PDF", true, null))
            {
                this.errorLabel.Text = "错误：请选择PDF类型文件";
                flag = false;
            }
            else
            {
                PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
                if (null != pdf)
                {
                    //文件大小不能超过10M
                    if (pdf.FileLength >= 10 * 1024 * 1024)
                    {
                        this.errorLabel.Text = "错误：选择的文件大小超过了10M";
                        pdf.Close();
                        return false;
                    }

                    this.ysTextBox.Text = pdf.NumberOfPages.ToString();
                }

                pdf.Close();
            }
        }
        return flag;
    }

   protected void resetButton_Click(object sender, EventArgs e)
    {
        this.BindData();
    }
}